package com.stu.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;

public class TextValueView extends View {
	private Paint bg, txt, bdrp;
	private Rect bgr, bdr;
	private String text;
	private int textSize, width, height;

	public TextValueView(Context context) {
		super( context );
		init();
	}
	public TextValueView(Context context, AttributeSet attrs) {
		super(context, attrs);
		textSize = 0;
		width = 0;
		int[] attr = new int[] { android.R.attr.textSize, android.R.attr.width };
		TypedArray a = context.obtainStyledAttributes( attrs, attr );
		textSize = a.getDimensionPixelSize( 0, 12 );
		width = a.getDimensionPixelSize( 1, 20 );
		a.recycle();
		init();
	}
	
	private void init() {
		text = new String();
		bg = new Paint();
		bg.setColor( Color.LTGRAY );
		bgr = new Rect();
		bdr = new Rect();
		txt = new Paint();
		txt.setAntiAlias( true );
		txt.setColor( Color.BLUE );
		txt.setTextSize( textSize );
		txt.setTextAlign( Paint.Align.CENTER );
		txt.setTypeface( Typeface.MONOSPACE );
		bdrp = new Paint();
		bdrp.setStrokeWidth( 1 );
		bdrp.setColor( Color.BLACK );
		height = (int)(-txt.ascent() + txt.descent() + 10);
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		setMeasuredDimension( width, height );
	}
	
	public void setText( String t ) {
		text = t;
		invalidate();
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		bdr.left = 0;
		bdr.top = 0;
		bdr.right = getWidth();
		bdr.bottom = getHeight();
		bgr.left = bdr.left + 1;
		bgr.right = bdr.right - 1;
		bgr.top = bdr.top + 1;
		bgr.bottom = bdr.bottom - 1;;
		canvas.drawRect( bdr, bdrp );
		canvas.drawRect( bgr, bg );
		canvas.drawText( text, getWidth() / 2, getHeight() - 8, txt );
	}

}
